import {createRouter, createWebHashHistory} from "vue-router";
import Home from "../views/Home.vue";
import store from "../store";

const viewsVue = import.meta.glob('../views/**/*.vue')


let homeChildren = [];
for (let viewsVueKey in viewsVue) {
    const vueFileName = viewsVueKey.substring(viewsVueKey.lastIndexOf('/') + 1,viewsVueKey.lastIndexOf('.'));
    console.log(vueFileName)
    if(vueFileName === 'Home' || vueFileName === 'Login'){
        //home页 登录也不需要重新进菜单
        continue;
    }
    homeChildren.push({
        path: "/" + vueFileName,
        name: vueFileName,
        // meta: {
        //     title: '系统首页'
        // },
        component: viewsVue[viewsVueKey]
    })
}


const routes = [
    {
        path: '/',
        redirect: '/dashboard'
    }, {
        path: "/",
        name: "Home",
        component: Home,
        children: homeChildren
    }, {
        path: "/login",
        name: "Login",
        meta: {
            title: '登录'
        },
        component: () => import ( /* webpackChunkName: "login" */ "../views/Login.vue")
    }
];

const router = createRouter({
    history: createWebHashHistory(),
    routes
});


router.beforeEach((to, from, next) => {
    document.title = store.state.titleMap.get(to.name.toLowerCase()) || to.name;
    const role = localStorage.getItem('ms_username');
    if (!role && to.path !== '/login') {
        next('/login');
    } else if (to.meta.permission) {
        // 如果是管理员权限则可进入，这里只是简单的模拟管理员权限而已
        role === 'admin'
            ? next()
            : next('/403');
    } else {
        next();
    }
});

export default router;